/**
 * 主要按钮
 * by zhangxinyue
 * create 2020-08-24
 *
 * sunwanli
 * edit 2021-08-13
 */
import React from 'react';
import PropTypes from 'prop-types';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Icon as LegacyIcon } from '@ant-design/compatible';
import { Button, Tooltip } from 'antd';

class PrimaryC extends React.PureComponent {
  // props默认值
  static defaultProps = {
    loading: false, // 默认不loading
    title: '', // 默认按钮无名称
    htmlType: 'button', // 默认不设置
    disabled: false, // 默认有效状态
    onClick: () => {}, // 默认无点击事件
    helper: undefined, // 帮助信息
    icon: undefined, // 默认按钮中不加图标
    style: undefined, // 样式
  };

  constructor(props) {
    super(props);
    this.state = {
      width: 0,
    };
  }

  componentDidMount() {
    let content = 0;
    const { title, loading, helper, icon } = this.props;
    content = icon ? 24 : 0;
    content = loading ? content + 24 : content + 0;
    content = helper ? content + 24 : content + 0;
    content = content + title.length * 14;
    this.setState({
      width: content,
    });
  }

  render() {
    const { title, loading, disabled, htmlType, onClick, style, helper, icon } = this.props;

    return (
      <div style={{ ...style, display: 'inline-block' }}>
        {helper ? (
          <Tooltip title={helper}>
            <Button type='primary' htmlType={htmlType} disabled={disabled} loading={loading} onClick={onClick} className={this.state.width > 56 ? 'long-content' : ''}>
              {title}
              <QuestionCircleOutlined />
            </Button>
          </Tooltip>
        ) : (
          <Button type='primary' htmlType={htmlType} disabled={disabled} loading={loading} onClick={onClick} className={this.state.width > 56 ? 'long-content' : ''}>
            {title}
            {icon && <LegacyIcon type={icon} />}
          </Button>
        )}
      </div>
    );
  }
}

// props类型
PrimaryC.propsTypes = {
  loading: PropTypes.bool, // 标记是否是loading状态
  title: PropTypes.string, // 按钮名称
  htmlType: PropTypes.oneOf(
    // 配合form表单的onSubmit事件，可设置值为“submit”
    ['submit', 'button', 'reset'],
  ),
  disabled: PropTypes.bool, // 标记是否是失效状态
  onClick: PropTypes.func, // 按钮点击事件
  style: PropTypes.object, // 样式
  helper: PropTypes.string, // 帮助信息
  icon: PropTypes.string, // 按钮中加图标(图标名称)
};

export default PrimaryC;
